package it.tukano.xprint;

import it.tukano.io.FileExt;
import it.tukano.xml.XmlDoc;
import it.tukano.xml.XmlDoc.XmlNode;
import java.util.ArrayList;
import java.util.List;

public class XPrint {
    
    public static class CssStyle {
        
        private XmlNode node;        
        
        private void create() {
            node.setTextContent(toString());
        }
        
        @Override
        public String toString() {
            StringBuilder buffer = new StringBuilder();
            buffer.append("@page { size: landscape; }\n");
            buffer.append("table { border-collapse:collapse; border: 1px solid black;}\n");
            buffer.append("tr { page-break-before: auto; }\n");
            buffer.append("td { font-size: small; border: 1px solid black; }");
            return buffer.toString();
        }
    }
    
    public static class XTable {
        private XmlNode node;
        private List<XmlNode> rows = new ArrayList<XmlNode>();
        
        public XTableRow appendRow() {
            XmlNode row = node.createChild("tr");
            rows.add(row);
            XTableRow tr = new XTableRow();
            tr.node = row;
            return tr;
        }
    };
    
    public static class XTableRow {
        private XmlNode node;
        
        public XTableCell addCell() {
            XTableCell cell = new XTableCell();
            cell.node = node.createChild("td");
            return cell;
        }
        
        public void setId(String id) {
            node.setId(id);
        }
    }
    
    public static class XTableCell {
        private XmlNode node;
        
        public void setText(String text) {
            node.setTextContent(text);
        }
    }
    
    public static void main(String[] args) {
        XPrint print = new XPrint();
        XTable table = print.appendTable("table001");
        XTableRow row = table.appendRow();
        XTableCell cell = row.addCell();
        cell.setText("Hello World!");
        print.print();
    }
    
    private final XmlDoc doc = XmlDoc.newInstance("html");
    private final XmlNode head, style, body;
    private final CssStyle css = new CssStyle();

    /**
     * Instance initializer
     */
    public XPrint() {
        head = doc.getRoot().createChild("head");
        body = doc.getRoot().createChild("body");
        style = head.createChild("style");
        css.node = style;
    }

    public XTable appendTable(String id) {
        XmlNode table = body.createChild("table");
        table.setId(id);
        XTable t = new XTable();
        t.node = table;
        return t;
    }
    
    public void print() {
        FileExt file = createTempFile();
        file.print();
    }

    private FileExt createTempFile() {
        css.create();
        FileExt file = FileExt.createTempFile("html");
        doc.store(file);
        return file;
    }
    
    public void open() {
        createTempFile().run();
    }
}
